package com.loie.xcx.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.loie.xcx.comm.JsonResult;
import com.loie.xcx.config.EmailConfig;
import com.loie.xcx.mapper.ApprovalformMapper;
import com.loie.xcx.model.bo.Approvalform;
import com.loie.xcx.model.bo.EmailBO;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;


@Slf4j
@Component
public class MailSend {
    @Autowired
    EmailConfig emailConfig;
    @Autowired
    ApprovalformMapper approvalformMapper;
    public  JsonResult<JSONObject> sendEmail(List<Approvalform> approvalformList) {
        //System.out.println(jsonStr);
        //EmailBO emailBO = JSONObject.parseObject(jsonStr, EmailBO.class);
        String emailNo;
        String content;
        String subject;
        //List<String> resultlist=new ArrayList<String>();

        if (approvalformList.size()==0){
            //resultlist.add("无邮件发送记录");
            return new JsonResult<>(400, "无邮件发送记录");
//            JSONObject jsonresult = new JSONObject();
//            jsonresult.put("result","无记录");
//            return jsonresult;
        }
        JSONArray jsonArray =new JSONArray();
        for (Approvalform approvalform : approvalformList) {
            JSONObject jsonresult = new JSONObject();
            if (approvalform != null) {
                emailNo = approvalform.getReceivemaillist();
                content = approvalform.getMemo();
                subject = approvalform.getSubject();
                //处理批量的情况,多邮箱会用;分隔
                String[] arr = emailNo.split(";");
                int receiverCount = arr.length;
                if (StringUtils.isNotBlank(emailNo) && StringUtils.isNotBlank(content) && receiverCount > 0) {
                    try {
                        // smtp端口
                        int port = Integer.parseInt(emailConfig.getPort());
                        // smtp服务器地址
                        String server = emailConfig.getUrl().trim();
                        // 发送者
                        String from = emailConfig.getFrom().trim();
                        String user = emailConfig.getUser().trim();
                        // 密码
                        String password = emailConfig.getPassword().trim();
                        Properties props = new Properties();
                        props.put("mail.smtp.host", server);
                        props.put("mail.smtp.port", port);
                        props.put("mail.smtp.auth", "true");
                        MailSSLSocketFactory sf = new MailSSLSocketFactory();
                        sf.setTrustAllHosts(true);
                        props.put("mail.smtp.ssl.enable", "true");
                        props.put("mail.smtp.ssl.socketFactory", sf);

                        Session session = Session.getDefaultInstance(props, null);
                        Transport transport = session.getTransport("smtp");
                        transport.connect(server, user, password);

                        InternetAddress[] address = new InternetAddress[receiverCount];
                        for (int i = 0; i < receiverCount; i++) {
                            address[i] = new InternetAddress(arr[i]);
                        }
                        MimeMessage msg = new MimeMessage(session);
                        msg.setSentDate(new Date());
                        msg.setFrom(new InternetAddress(from));
                        msg.setRecipients(Message.RecipientType.TO, address);
                        msg.setSubject(subject, "UTF-8");
                        msg.setSentDate(new Date());
                        msg.setContent(this.getHtml(content), "text/html;charset=utf-8");
                        transport.sendMessage(msg, msg.getAllRecipients());
                        transport.close();
                        approvalform.setIsSend(true);
                        //resultlist.add(approvalform.getSubject()+"发送至"+approvalform.getReceivelist()+"成功");
                        //return new JsonResult<>();
                        approvalformMapper.update_approvalform_send(approvalform);

                        jsonresult.put("sendto",approvalform.getSubject()+"发送至"+approvalform.getReceivelist()+"成功");

                    } catch (Exception e) {
                        //log.error("EmailChannel.sendEmail===>邮件发送异常！", e);
                        //resultlist.add(approvalform.getSubject()+"发送异常："+e);
                        jsonresult.put("sendto",approvalform.getSubject()+"发送异常"+e);

                    }
                }
            }

            jsonArray.add(jsonresult);
        }
        //return new JsonResult<>(400, "发送失败");
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("sendlist",jsonArray);
        jsonObject1.put("list",approvalformList.size());
        //return jsonObject1;
        return  new JsonResult<>(jsonObject1);
        //return jsonArray;
    }

        private String getHtml(String msg) {
        String content = "<!doctype html> " + "<html> " + "<head> " + "<meta charset=\"gb2312\">" + " <title></title> " + "</head> " + " <div class=\"link\" style=' float:right; height:30px; padding:50px 0 3px 0;font-family:\"Microsoft Yahei\";'> "
                + " </div> " + "<div id=\"center\" style=' margin:0 auto; width:650px; background:#f1f1f1; padding:24px 0 0 0 ; '>  ";
        content = content + "<div style=\" width:563px;  margin:0 auto 0 auto; padding:15px 20px; line-height:40px; font-size:14px; background:#00EE76; color:#000000; \">"
                + "<span style=\"font-size:24px; font-weight:bold;\">" + msg + "</span>" +
                "<br/><hr/><span style=\"font-size:16px;\">请登录系统查看详情，本邮件由系统自动发出，请勿直接回复！</span>";
        content = content + "</div> ";
        content = content + "<div class='clear'>" + "</div> " + "<div id='foot' style='margin:0 auto; width:610px; font-size:12px; color:#333333; line-height:30px; padding:15px 20px; background:#f1f1f1;'></div></body></html>";
        return content;
    }
//    public static void main(String[] args) {
//
////        JSONObject jsonObject = new JSONObject();
////        jsonObject.put("emailNo","hopelucky66@163.com;Kevin_xu@link-int.com");
////        jsonObject.put("content","批复内容：请注意包装箱唛是否准备无误");
////        jsonObject.put("subject","批复意见通知/采购合同ABCDEF");
////        JsonResult<EmailBO> message=sendEmail(jsonObject.toString());
////        System.out.println(message);
//
//    }
}
